<template>
  <n-form-item :label="label" :path="name">
    <n-upload
        ref="uploadRef"
        :data="data"
        :action="baseURL + 'api/doc/file/upload'"
        :headers="{
          Authorization:token
        }"
        :max="1"
        @finish="onFinish"
        list-type="image-card"
        accept=".jpg,.jpeg,.png,.webp"
    >
      <n-button>上传文件</n-button>
    </n-upload>
  </n-form-item>
</template>
<script setup >
import cacheUtil from "@/utils/cacheUtil";
const baseURL = import.meta.env.VITE_APP_BASE_API;
const token = computed(()=>cacheUtil.session.get('token'))
const uploadRef = ref()
const props = defineProps({
  label:String,
  name:String,
  required:Boolean,
  rules:Object,
  data:Object,
  value:[Number,null]
})
const emit = defineEmits(['loadRules','finish','update:value'])
onMounted(()=>{
  emit('loadRules',props)
})
function onFinish(options){
  const {file,event} = options
  let data = {file:file}
  if (event?.currentTarget?.response){
    let res = JSON.parse(event?.currentTarget?.response);
    data.data = res.data
    emit('update:value',res.data?.id)
  }
  emit('finish',data);
}
function  openOpenFileDialog (){
  uploadRef.value?.openOpenFileDialog()
}
defineExpose({
  openOpenFileDialog: openOpenFileDialog
})
</script>
